package com.guangli.base.utils;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import com.blankj.utilcode.util.ImageUtils;
import com.guangli.base.util.AppUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

/**
 * 创建日期：2021/10/11  09:38
 * 类说明:
 *
 * @author：86152
 */
public class GlassMediaUtils {


    /**
     * 保存到SD卡
     */
    private static final String SAVE_PIC_PATH = Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED) ? Environment.getExternalStorageDirectory().getAbsolutePath() : "/mnt/sdcard";

    /**
     * 图片存储路径
     */
    public static final String LOCAL_GALLERY_PATH = SAVE_PIC_PATH + "/rokid/capture/img/";

    /**
     * 视屏存储路径
     */
    public static final String LOCAL_VIDEO_PATH = SAVE_PIC_PATH + "/rokid/capture/video/";

    /**
     * 文件存储路径
     */
    public static final String LOCAL_FILE_PATH = SAVE_PIC_PATH + "/rokid/capture/file/";

    /**
     * 保存图片到本地相册
     */
    public static File saveImageToLocalGallery(Bitmap img, String taskId) {
        File file = new File(LOCAL_GALLERY_PATH + taskId + "/" + getFileName() + ".jpg");
        ImageUtils.save(img, file, Bitmap.CompressFormat.JPEG);
        Uri uri = Uri.fromFile(file);
        AppUtils.getApp().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        return file;
    }

    public static String getFileName() {
        Calendar now = new GregorianCalendar();
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        return simpleDate.format(now.getTime());
    }

    /**
     * 从sd卡获取图片资源
     *
     * @return
     */
    public static List<String> getImagePathFromSD() {
        // 图片列表
        List<String> imagePathList = new ArrayList<String>();
        // 得到sd卡内image文件夹的路径   File.separator(/)
        String filePath = LOCAL_GALLERY_PATH;
        // 得到该路径文件夹下所有的文件
        File fileAll = new File(filePath);
        File[] files = fileAll.listFiles();
        if (files == null || files.length == 0) {
            return imagePathList;
        }
        // 将所有的文件存入ArrayList中,并过滤所有图片格式的文件
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (checkIsImageFile(file.getPath())) {
                imagePathList.add(file.getPath());
            }
        }
        sort(imagePathList);
        // 返回得到的图片列表
        return imagePathList;
    }

    /**
     * 从sd卡获取图片资源
     *
     * @return
     */
    public static List<String> getImagePathFromSD(String taskId) {
        // 图片列表
        List<String> imagePathList = new ArrayList<String>();
        // 得到sd卡内image文件夹的路径   File.separator(/)
        String filePath = LOCAL_GALLERY_PATH + taskId + "/";
        // 得到该路径文件夹下所有的文件
        File fileAll = new File(filePath);
        File[] files = fileAll.listFiles();
        if (files == null || files.length == 0) {
            return imagePathList;
        }
        // 将所有的文件存入ArrayList中,并过滤所有图片格式的文件
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (checkIsImageFile(file.getPath())) {
                imagePathList.add(file.getPath());
            }
        }
        sort(imagePathList);
        // 返回得到的图片列表
        return imagePathList;
    }

    private static void sort(List<String> imgs) {
        Collections.sort(imgs, new MyComparator());
    }

    public static class MyComparator implements Comparator<String> {
        @Override
        public int compare(String vo1, String vo2) {
            // TODO Auto-generated method stub
            File file1 = new File(vo1);
            File file2 = new File(vo2);
            long file1Time1 = file1.lastModified();
            long fileTime2 = file2.lastModified();
            if (file1Time1 > fileTime2) {
                return -1;
            } else if (file1Time1 == fileTime2) {
                return 0;
            } else {
                return 1;
            }
        }
    }

    /**
     * 从sd卡获取图片资源
     *
     * @return
     */
    public static List<String> getVideoPathFromSD() {
        // 图片列表
        List<String> imagePathList = new ArrayList<String>();
        // 得到sd卡内image文件夹的路径   File.separator(/)
        String filePath = LOCAL_VIDEO_PATH;
        // 得到该路径文件夹下所有的文件
        File fileAll = new File(filePath);
        if(fileAll.isDirectory()){

        }
        File[] files = fileAll.listFiles();
        if (files == null || files.length == 0) {
            return imagePathList;
        }
        // 将所有的文件存入ArrayList中,并过滤所有图片格式的文件
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (checkIsVideoFile(file.getPath())) {
                imagePathList.add(file.getPath());
            }
        }
        sort(imagePathList);
        // 返回得到的图片列表
        return imagePathList;
    }

    /**
     * 从sd卡获取图片资源
     *
     * @return
     */
    public static List<String> getVideoPathFromSD(String taskId) {
        // 图片列表
        List<String> imagePathList = new ArrayList<String>();
        // 得到sd卡内image文件夹的路径   File.separator(/)
        String filePath = LOCAL_VIDEO_PATH + taskId + "/";
        // 得到该路径文件夹下所有的文件
        File fileAll = new File(filePath);
        File[] files = fileAll.listFiles();
        if (files == null || files.length == 0) {
            return imagePathList;
        }
        // 将所有的文件存入ArrayList中,并过滤所有图片格式的文件
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (checkIsVideoFile(file.getPath())) {
                imagePathList.add(file.getPath());
            }
        }

        sort(imagePathList);
        // 返回得到的图片列表
        return imagePathList;
    }

    /**
     * 检查扩展名，得到图片格式的文件
     *
     * @param fName 文件名
     * @return
     */
    @SuppressLint("DefaultLocale")
    private static boolean checkIsImageFile(String fName) {
        boolean isImageFile = false;
        // 获取扩展名
        String FileEnd = fName.substring(fName.lastIndexOf(".") + 1,
                fName.length()).toLowerCase();
        if (FileEnd.equals("jpg") || FileEnd.equals("png") || FileEnd.equals("gif")
                || FileEnd.equals("jpeg") || FileEnd.equals("bmp")) {
            isImageFile = true;
        } else {
            isImageFile = false;
        }
        return isImageFile;
    }

    /**
     * 检查扩展名，得到图片格式的文件
     *
     * @param fName 文件名
     * @return
     */
    @SuppressLint("DefaultLocale")
    private static boolean checkIsVideoFile(String fName) {
        boolean isImageFile = false;
        // 获取扩展名
        String FileEnd = fName.substring(fName.lastIndexOf(".") + 1,
                fName.length()).toLowerCase();
        if (FileEnd.equals("mp4") || FileEnd.equals("3gp") || FileEnd.equals("rmvb")) {
            isImageFile = true;
        } else {
            isImageFile = false;
        }
        return isImageFile;
    }


    public static long getPlayTime(String mUri) {
        android.media.MediaMetadataRetriever mmr = new android.media.MediaMetadataRetriever();
        try {
            if (mUri != null) {
                HashMap<String, String> headers = null;
                if (headers == null) {
                    headers = new HashMap<String, String>();
                    headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
                }
                mmr.setDataSource(mUri, headers);
            } else {
                //mmr.setDataSource(mFD, mOffset, mLength);
            }

            String duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);//时长(毫秒)
            String width = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);//宽
            String height = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);//高
            return Long.parseLong(duration);
        } catch (Exception ex) {
            Log.e("TAG", "MediaMetadataRetriever exception " + ex);
        } finally {
            mmr.release();
        }
        return 0;
    }

    /**
     * 保存图片到本地相册
     */
    public static File saveImage(Bitmap img) {
        File file = new File(LOCAL_FILE_PATH + getFileName() + ".jpg");
        ImageUtils.save(img, file, Bitmap.CompressFormat.JPEG);
        Uri uri = Uri.fromFile(file);
        AppUtils.getApp().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        return file;
    }

    /**
     * 保存图片到本地相册
     */
    public static File saveImage1(Bitmap img, String str) {
        File file = new File(LOCAL_FILE_PATH + getFileName() + str + ".jpg");
        ImageUtils.save(img, file, Bitmap.CompressFormat.JPEG);
        Uri uri = Uri.fromFile(file);
        AppUtils.getApp().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        return file;
    }

    public static void writeFile(String fileName, byte[] buffer) {
        File file = new File(fileName);
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "rw");
            raf.seek(file.length());
            raf.write(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (raf != null) {
                    raf.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Bitmap rawByteArray2RGBABitmap2(byte[] data, int width, int height) {
        YuvImage img = new YuvImage(data, ImageFormat.NV21, width, height, null);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        img.compressToJpeg(new Rect(0, 0, width, height), 80, stream);
        Bitmap bitmap = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
        try {
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}
